// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import '@/css/reset.scss'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import api from './js/api.js';
import store from './vuex/store';
import Vuex from 'vuex';
import axios from 'axios';
import qs from 'qs';

Vue.config.productionTip = false

axios.defaults.withCredentials = false; // 是否允许携带cookie
Vue.prototype.$http = axios;
Vue.prototype.$api = api;
Vue.prototype.$qs = qs;

Vue.use(Vuex);
Vue.use(ElementUI);

// 页面刷新时，重新赋值
if (sessionStorage.getItem('token')) {
  store.commit('set_token', sessionStorage.getItem('token'));
}

router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.requireAuth)) {
    // 这里的requireAuth为路由中定义的 meta:{requireAuth:true}
    // 意思为：该路由添加该字段，表示进入该路由需要登陆的
    if (store.state.token) {
      next();
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      });
    }
  } else {
    next();
  }
});

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.data.code == -1001) {
      console.log('登录已超时');
      router.replace({
        path: '/login'
      });
    }
    return response;
  },
  error => {
    // 对请求错误做些什么
    if (error.response) {
      console.log(error.response);
    }
    return Promise.reject(error);
  }
);

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})
